<template>
	<div class="login">
		<div class="logoImg">
			<img slot="icon" style="width: 50%" src="../assets/logo.jpg">
		</div>
		<h3 style="text-align: center;color: rgb(255, 142, 10);">更多商机，更好口碑</h3>
		<group style="margin-top: 40px">
			<x-input title="用户" name="mobile" placeholder="请输入手机号码" v-model="mobile" keyboard="number" is-type="china-mobile" required></x-input>
			<x-input title="密码"  :type="pwdType" placeholder="请输入密码" v-model="password" :min="6" :max="16" @on-change="change" required>
				<input slot="right" type="checkbox" @click="changeType"/>
			</x-input>
		</group>
		<div class="error" v-show="error">{{error}}</div>
		<flexbox style="margin-top: 40px">
			<flexbox-item>
				<x-button :gradients="['#1D62F0', '#19D5FD']" @click.native="handleLogin">登录</x-button>
			</flexbox-item>
			<flexbox-item>
				<x-button :gradients="['#FF5E3A', '#FF9500']" @click.native="register">开通免费试用</x-button>
			</flexbox-item>
		</flexbox>
		<!--<p><span class="forget-pass">	<router-link to="/forgetpwd">忘记密码?</router-link></span></p>
		<x-button :gradients="['#1D62F0', '#19D5FD']" style="margin-top: 40px;width: 80%" @click.native="handleLogin">登录</x-button>
		<div style="text-align: center;margin-top: 20px">或者</div>
		<x-button :gradients="['#FF5E3A', '#FF9500']" style="margin-top: 20px;width: 80%" @click.native="register">免费试用</x-button>-->
		<actionsheet
			class="loginActionSheet"
			v-model="show"
			:menus="menu"
			theme="android"
			@on-click-menu="click"
			@on-after-hide="log('after hide')"
			@on-after-show="log('after show')">
			<p slot="header" v-html="actionHeader"></p>
		</actionsheet>

	</div>
</template>

<script>
	import NetWorking from '../../../utils/networking'
	import qs from 'qs'
	import { XInput,Box, Group, XButton, Actionsheet, Flexbox, FlexboxItem } from 'vux'
	export default {
		name: 'login',
        props: {
            openid: {
              type: String,
              default: ''
            }
        },
		data() {
			return {
			    dopenid:this.openid,
				actionHeader: '请选择你以什么角色登录系统',
				show: false,
				menu: {},
				mobile:'',//用户手机号
				password:'',//用户密码
				isLogining: false,
				error: false,
				pwdType:'password',
				isAndroid: false,
				isWechat: false,
				isIOS: false
			}
		},
		components: {
			Actionsheet,
			XInput,
			XButton,
			Group,
			Box,
			Flexbox,
			FlexboxItem
		},
		created: function () {
			if(navigator.userAgent.match('Android')){
				this.isAndroid = true
			}

			if(navigator.userAgent.match('iPhone')){
				this.isiOS = true
			}

			if(navigator.userAgent.match('MicroMessenger')){
				this.isWechat = true
			}
			if(this.$route.query.openid != null){
			    this.$store.commit('SET_WXOPENID', this.$route.query.openid)
			}
			
		},
		methods:{
			register() {
			    this.$router.push({ name: 'register'})
			},
			addToMenu (value) {
				return '以' + value + '身份登录系统'
			},
			click (key, item) {
				switch (key) {
					case 'teacher':
						this.$store.commit('CREATE_LAST_LOGIN_AS', 'teacher')
						location.replace('/mavinTeacher')
						break
					case 'consultant':
						this.$store.commit('CREATE_LAST_LOGIN_AS', 'consultant')
						location.replace('/mavinSales')
						break
				}
			},

			changeType(){
				this.pwdType = this.pwdType==='password'?'text':'password';
			},

			showLoading () {
				this.isLogining = true
			},

			hideLoading () {
				this.isLogining = false
			},

			change (val) {
				console.log('on change', val)
			},

			wxAppLogin(){
				if (typeof Wechat === "undefined") {
					alert("Wechat plugin is not installed.")
					return false;
				}

				let scope = "snsapi_userinfo"
				let	state = "_" + (+new Date())
				//Step 1, request the code
				Wechat.auth(scope, state, function (response) {
					// you may use response.code to get the access token.
					alert("CODE: " + response.code)
					NetWorking.doGet(
						'utils/getAppWxToken',
						null,
						{
							params:{
								code: response.code
							}
						}
					).then(
						response => {
							let res = response.data
						}
					)
				}, function (reason) {
					alert("Failed: " + reason)
				})
			},

			handleLogin(){
				if(this.mobile =='' && this.password ==''){
					this.error = "请确认用户名或者密码输入正确"
					return;
				}

				//一般要跟后端了解密码的加密规则
				//这里例子用的哈希算法来自./js/sha1.min.js
				//let password_sha = hex_sha1(hex_sha1( this.pwd ));

				//_this.$store.commit('CREATE_WXOPENID', )

				//需要想后端发送的登录参数
				let loginParam = {
					username: this.mobile,
					password:this.password,
				    openid:this.$store.state.user.openid
				}

				//设置在登录状态
				this.isLogining = true
				let _this = this


				//请求后端,比如:
				NetWorking.doPost(
					'auth/login',
					null,
					qs.stringify(loginParam),
					{
						headers: {
							'Content-Type': 'application/x-www-form-urlencoded'
						}
					}
				).then(
					response => {
						let res = response.data
						if (res.error_code == 0)
						{
						    _this.$store.commit('DELETE_WXOPENID')
							_this.$store.commit('CREATE_TOKEN', res.token)
							_this.$store.commit('CREATE_USER_MODEL', res.user_model)

							for(var i=0; i< res.user_model.sysRoleList.length; i++){
								switch (res.user_model.sysRoleList[i].role_name){
									case 'teacher':
										_this.menu.teacher = _this.addToMenu(res.user_model.sysRoleList[i].role_description)
										if(res.user_model.sysRoleList.length == 1){
											_this.$store.commit('CREATE_LAST_LOGIN_AS', 'teacher')
											location.replace('/mavinTeacher')
										}
										break
									case 'consultant':
										_this.menu.consultant = _this.addToMenu(res.user_model.sysRoleList[i].role_description)
										if(res.user_model.sysRoleList.length == 1){
											_this.$store.commit('CREATE_LAST_LOGIN_AS', 'consultant')
											location.replace('/mavinSales')
										}
										break
									default:
										break
								}
								_this.show = true
							}
						}
						else if (res.error_code == 20005)
						{
							_this.error = "该账户不存在，请点击注册进行注册!"
						}
						else
						{
							_this.error = res.error_message
						}
						_this.hideLoading()
					},
					(message) => {
						window.alert(message)
						this.hideLoading()
					}
				)
			}
		}
	}
</script>

<style lang="less">
	@color666:#666666;
	@color393a31:#393a31;
	.input-box{
		background-color: #FFFFFF;
	}
	.login{
		margin-top: 50px;
		>p:first-of-type{
			padding: 20px 15px 40px;
			float: right;
			color: @color666;
			font-size:14px;
		}
		>p:last-of-type{
			width: 100%;
			text-align: center;
			color: @color393a31;
			font-size:14px;
			position: absolute;
			bottom: 25px;
		}
	}
	.error{
		margin-top: 10px;
		font-size: 15px;
		color:red;
		text-align: center;
	}
	.icon-wx{
		width: 40px;
		margin-top: 50px;
	}
	.logoImg {
		text-align: center;
	}

	.commonBtn{
		margin-top: 40px;
		width: 80%;
	}

	.loginActionSheet > .weui-skin_android > .weui-actionsheet > .weui-actionsheet__menu{
		background: lightslategrey;
		color: white;
		border-radius: 25px;
	}
</style>
